package com.cloudkinto.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.common.MD5Util;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.dao.UserDao;
import com.cloudkinto.entity.UserDo;
import com.cloudkinto.entity.WxUserDo;
import com.cloudkinto.service.user.wxvo.WxTokenByCodeEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cloudkinto.service.user.WxUserService;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.Map;

import com.cloudkinto.base.BaseController;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author zhangyy
 * @since 2020-10-09
 */
@RestController
@Api(tags = "微信公众号模块")
@RequestMapping("/api/admin/weChat")
public class WxUserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(WxUserController.class);

    @Autowired
    private WxUserService service;
    @Autowired
    private UserDao userDao;

    @GetMapping("/getAccessTokenByCode")
    @ApiOperation(value = "根据code获取token在获取user信息", notes = "根据code获取token在获取user信息")
    public SingleResult getTokenByCode(@RequestParam String code,@RequestParam String userAccount,@RequestParam String password) {
        MD5Util md5 = new MD5Util(SysConstant.SALT_STRING, "MD5");
        LambdaQueryWrapper<UserDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDo::getUserAccount, userAccount)
                .eq(UserDo::getUserPassword, md5.encode(password));

        UserDo userDo = userDao.selectOne(wrapper);
        if (userDo == null) {
            throw new BizException(SysConstant.WxUser_Auth_Error);
        }

        //1.根据code获取token以及openid
        WxTokenByCodeEntity wxTokenByCodeEntity = service.getAccessTokenByCode(code);
        //获取微信用户信息并保存
        WxUserDo userInfoByToken = service.getUserInfoByToken(wxTokenByCodeEntity.getAccess_token(), wxTokenByCodeEntity.getOpenid(), userDo.getId(),userDo.getCompanyId());

        return SingleResult.success(userInfoByToken);
    }


}

